#pragma once
#include <iostream>
#include <string>
#include <strings.h>
#include <cstring>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <functional>
#include "Log.hpp"
using func_t = std::function<std::string(const std::string &)>;
using namespace std;

enum
{
    SOCKET_ERROR = 1,
    BIND_ERROR
};

uint16_t defaultport = 8080;
string defaultip = "0.0.0.0";
const int size = 1024;
Log lg;

class UdpServer
{
public:
    UdpServer(const uint16_t &port = defaultport, const string &ip = defaultip)
        : _sockfd(0), _port(port), _ip(ip), _isrunning(false)
    {
    }
    void Init()
    {
        // 1. 创建UDP socket
        _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
        if (_sockfd < 0)
        {
            lg(Fatal, "socket create error, sockfd: %d", _sockfd);
            exit(SOCKET_ERROR);
        }
        lg(Info, "socket create success, sockfd: %d", _sockfd);

        // 2. 绑定socket
        struct sockaddr_in local;
        bzero(&local, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(_port);
        local.sin_addr.s_addr = inet_addr(_ip.c_str());

        if (bind(_sockfd, (const struct sockaddr *)&local, sizeof(local)) < 0)
        {
            lg(Fatal, "bind error, errno: %d, err string: %s", errno, strerror(errno));
            exit(BIND_ERROR);
        }
        lg(Info, "bind success, errno: %d, err string: %s", errno, strerror(errno));
    }
    void Run() // 对代码进行分层
    {
        _isrunning = true;
        char inbuffer[size];
        while (_isrunning)
        {
            struct sockaddr_in client;
            socklen_t len = sizeof(client);
            ssize_t n = recvfrom(_sockfd, inbuffer, sizeof(inbuffer) - 1, 0, (struct sockaddr *)&client, &len);
            if (n < 0)
            {
                lg(Warning, "recvfrom error, errno: %d, err string: %s", errno, strerror(errno));
                continue;
            }
            inbuffer[n] = 0;
            string info = inbuffer;
            string echo_string = "sever echo#" + info;
            cout << echo_string << endl;
            sendto(_sockfd, echo_string.c_str(), echo_string.size(), 0, (const sockaddr *)&client, len);
        }
    }
    ~UdpServer()
    {
        if (_sockfd > 0)
            close(_sockfd);
    }

private:
    int _sockfd;
    string _ip;
    uint16_t _port;
    bool _isrunning;
};